import { asyncRouterMap , constantRouterMap } from '@/router'

const _import = require('@/router/_import_' + process.env.NODE_ENV)
import Layout from '@/views/layout/Layout'

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param roles
 */


const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        let accessedRouters=[];
        // 重新组装一份数据  因为import是个方法
        // accessedRouters.forEach((item, index) => {
        //   item.redirect = 'noredirect'
        //   item.component = Layout
        //   item.children.forEach((child, index) => {
        //     let link = child.component
        //     child.component = _import(link)
        //   })
        // })
        // const other = { path: '*', redirect: '/404', hidden: true }
        // accessedRouters.push(other)


        //下面只是为了方便本地测试
        accessedRouters=asyncRouterMap

        console.log(accessedRouters)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
